#include <vector>
#include <iostream>
#include <string>
#include "conio.h"

using namespace std;

// -1 = correct
// other - length of correct prefix (with possible addition)
int check_brackets_string(const string &brackets)
{
	vector<char> stack_of_brackets;
	bool mistmatch = false;
	int n_mutually_destructed_pairs = 0;

	stack_of_brackets.reserve(brackets.size());
	for (int i_ch = 0; i_ch < static_cast<int>(brackets.size()); i_ch++)
	{
		char cur_char = brackets[i_ch];		
		if (cur_char == ')' || cur_char == ']' || cur_char == '}')
		{			
			if (stack_of_brackets.size() > 0)
			{
				char char_at_the_top = stack_of_brackets.back();

				// found mistmatch
				if (!((cur_char == ')' && char_at_the_top == '(') ||
					(cur_char == '}' && char_at_the_top == '{') ||
					(cur_char == ']' && char_at_the_top == '[')))
				{
					mistmatch = true;
					break;
				}
				else
				{
					stack_of_brackets.pop_back();
					n_mutually_destructed_pairs++;
				}
			}
			else	// or stack is empty
			{
				mistmatch = true;
				break;
			}
		}
		else
			stack_of_brackets.push_back(cur_char);
	}

	// if something have been left in the stack
	if (stack_of_brackets.size() > 0)
		mistmatch = true;

	if (mistmatch)
		return 2 * n_mutually_destructed_pairs + stack_of_brackets.size();
	else
		return -1;
}

void main()
{
	string brackets;
	cout << "Input brackets sequence:" << endl;
	cin >> brackets;

	int res = check_brackets_string(brackets);
	cout << "Result = " << res << endl;
	_getch();
}